package com.village.friend.sms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dahantc.api.sms.json.JSONHttpClient;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.dto.response.BaseResponse;
import com.village.friend.exception.AppRuntimeException;
import com.village.friend.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 大汉三通短信服务
 *
 */
@Service
@Slf4j
public class DhstSmsService implements SmsBaseService{

    @Autowired
    private RedisService redisService;

    private JSONHttpClient jsonHttpClient;


//    public static void main(String[] args) throws URIException {
//        SmsService smsService = new SmsService();
//        smsService.agentSmsName = "慧信生活";
//        smsService.sendPlanFailedNotify("15200850561", "1111");
//    }

    @Value("${sms.namebase64}")
    private String agentSmsNameBase64;
    private String agentSmsName;

    private String smsAccount = "dh43176";
    private String smsPwd = "yeN7S9w1";
    private String smsSubcode = "";

    public DhstSmsService() throws URIException {
        jsonHttpClient = new JSONHttpClient("http://www.dh3t.com");
    }

    /**
     * 提交单条普通短信
     */
    public boolean sendVerifyCode(String phone, String valicode) {
        log.info("发送验证码to[" + phone + "]" + valicode);
        String response =  jsonHttpClient.sendSms(smsAccount, smsPwd, phone,//
                valicode + "是您本次的验证码，请在1分钟内正确输入，请勿泄露此验证码。",//
                "【" + getAgentSmsName() + "】",//
                smsSubcode);//
        if(response == null){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(response);

        return jsonObject != null && jsonObject.get("result").equals("0");
    }

    public String sendPlanFailedNotify(String phone, String content) {
        return jsonHttpClient.sendSms(smsAccount, smsPwd, phone,//
                content, "【" + getAgentSmsName() + "】",//
                smsSubcode);//
    }

    public String getAgentSmsName() {
        if (agentSmsName == null) {
            byte[] bs = Base64.decodeBase64(agentSmsNameBase64);
            agentSmsName = new String(bs, StandardCharsets.UTF_8);
        }
        return agentSmsName;
    }

    /**
     * 获取状态报告
     *
     * @return
     */
    public String getReport() {
        log.info("获取状态报告开始...");
        return jsonHttpClient.getReport(smsAccount, smsPwd);
    }

    public SmsResultBean parseReportResponse(String response){
        Map<String, Object> reportMap = (Map) JSONObject.parse(response);
        if (reportMap.get("result").equals("0")) {
            // 暂时没有获取是否接收成功
            JSONArray reportsArray = (JSONArray) reportMap.get("reports");
            Map<String, Object> newReportMap = (Map) reportsArray.get(0);
            if (newReportMap.get("wgcode").equals("DELIVRD") || newReportMap.get("wgcode").equals("0")) {
                return new SmsResultBean(true,"");
            }else {
                return new SmsResultBean(false,"");

            }
        }else {
            return new SmsResultBean(false,"");
        }
    }

    /**
     * 获取上行短信
     *
     * @return
     */
    public String getSms() {
        return jsonHttpClient.getSms(smsAccount, smsPwd);
    }

    /**
     * 验证码校验服务
     *
     * @param dtoPhone
     * @param dtoCode
     * @return
     */
    public BaseResponse validateSmscode(String dtoPhone, String dtoCode) {
        // 验证redis中是否验证码一致
        String code = redisService.get(dtoPhone);
        if (StringUtils.isEmpty(code)) {
            throw new AppRuntimeException("验证码已失效！请重新获取！");
        }
        else if (!code.equals(dtoCode)) {
            throw new AppRuntimeException("验证码输入不正确！");
        }else {
            return new BaseResponse(MsgCodeEnum.SUCCESS, null);
        }
    }

    public static void main(String[] args) throws Exception {
        DhstSmsService smsService = new DhstSmsService();
        boolean b = smsService.sendVerifyCode("19120823203", "1111");
        log.info("返回状态:" + b);
    }
}
